"""
评论管理
"""
from flask import Blueprint, render_template, request, jsonify
from apps.common.utils.rights import authorize
from apps.modules.admin.models.cms.cms_comment import Comment
from apps.modules.admin.models.cms.cms_post import Post
from apps.extensions import db
from sqlalchemy import or_, and_
import datetime

comment_bp = Blueprint('comment', __name__, url_prefix='/comment')

@comment_bp.get('/')
@authorize("cms:comment:main")
def index():
    """评论管理主页面"""
    return render_template('cms/comment/main.html')

@comment_bp.get('/list')
@authorize("cms:comment:main")
def get_comment_list():
    """获取评论列表"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status', '')  # 空字符串表示全部状态
        search = request.args.get('search', '')
        comment_type = request.args.get('comment_type', 'all')
        
        # 构建查询
        query = Comment.query.filter(Comment.deleted == False)
        
        # 状态筛选 - 只有当status不为空且不等于'all'时才筛选
        if status and status != 'all':
            query = query.filter(Comment.status == status)
        
        # 搜索功能
        if search:
            search_filter = or_(
                Comment.author.contains(search),
                Comment.content.contains(search),
                Comment.email.contains(search),
                Comment.ip.contains(search)
            )
            query = query.filter(search_filter)
        
        # 评论类型筛选（这里可以根据article_id来区分文章评论和页面评论）
        if comment_type != 'all':
            # 这里需要根据实际的文章类型字段来实现
            pass
        
        # 排序（按创建时间倒序）
        query = query.order_by(Comment.created_at.desc())
        
        # 分页
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        # 获取关联的文章信息
        comments = []
        for comment in pagination.items:
            article = None
            if comment.article_id:
                try:
                    # 尝试从Article表查询
                    article = Article.query.get(comment.article_id)
                except:
                    # 如果Article表不存在，使用默认值
                    article = None
            
            comment_data = {
                'id': comment.id,
                'author': comment.author,
                'email': comment.email,
                'url': comment.url,
                'ip': comment.ip,
                'content': comment.content,
                'status': comment.status,
                'article_id': comment.article_id,
                'created_at': comment.created_at.strftime('%Y-%m-%d %H:%M') if comment.created_at else '',
                'updated_at': comment.updated_at.strftime('%Y-%m-%d %H:%M') if comment.updated_at else '',
                'article_title': article.title if article else f'文章{comment.article_id}' if comment.article_id else '未知文章',
                'article_url': f'/article/{article.id}' if article else '#'
            }
            comments.append(comment_data)
        
        # 统计各状态数量
        try:
            status_counts = {
                'all': Comment.query.filter(Comment.deleted == False).count(),
                'pending': Comment.query.filter(and_(Comment.deleted == False, Comment.status == 'pending')).count(),
                'approved': Comment.query.filter(and_(Comment.deleted == False, Comment.status == 'approved')).count(),
                'spam': Comment.query.filter(and_(Comment.deleted == False, Comment.status == 'spam')).count(),
                'trash': Comment.query.filter(and_(Comment.deleted == False, Comment.status == 'trash')).count()
            }
        except:
            # 如果查询失败，返回默认值
            status_counts = {
                'all': 0,
                'pending': 0,
                'approved': 0,
                'spam': 0,
                'trash': 0
            }
        
        return jsonify({
            'code': 200,
            'msg': '获取成功',
            'data': {
                'comments': comments,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'has_prev': pagination.has_prev,
                    'has_next': pagination.has_next
                },
                'status_counts': status_counts
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 200,  # 改为200，避免前端报错
            'msg': '暂无数据',
            'data': {
                'comments': [],
                'pagination': {
                    'page': 1,
                    'per_page': 10,
                    'total': 0,
                    'pages': 0,
                    'has_prev': False,
                    'has_next': False
                },
                'status_counts': {
                    'all': 0,
                    'pending': 0,
                    'approved': 0,
                    'spam': 0,
                    'trash': 0
                }
            }
        })

@comment_bp.post('/update_status')
@authorize("cms:comment:main")
def update_comment_status():
    """更新评论状态"""
    try:
        data = request.get_json()
        comment_id = data.get('comment_id')
        status = data.get('status')
        
        if not comment_id or not status:
            return jsonify({
                'code': 400,
                'msg': '参数不完整',
                'data': None
            })
        
        comment = Comment.query.get(comment_id)
        if not comment:
            return jsonify({
                'code': 404,
                'msg': '评论不存在',
                'data': None
            })
        
        comment.status = status
        comment.updated_at = datetime.datetime.now()
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'msg': '状态更新成功',
            'data': None
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'msg': f'状态更新失败: {str(e)}',
            'data': None
        })

@comment_bp.post('/batch_update')
@authorize("cms:comment:main")
def batch_update_comments():
    """批量更新评论"""
    try:
        data = request.get_json()
        comment_ids = data.get('comment_ids', [])
        action = data.get('action')  # approve, reject, spam, trash, delete
        
        if not comment_ids or not action:
            return jsonify({
                'code': 400,
                'msg': '参数不完整',
                'data': None
            })
        
        comments = Comment.query.filter(Comment.id.in_(comment_ids)).all()
        
        for comment in comments:
            if action == 'approve':
                comment.status = 'approved'
            elif action == 'reject':
                comment.status = 'pending'
            elif action == 'spam':
                comment.status = 'spam'
            elif action == 'trash':
                comment.status = 'trash'
            elif action == 'delete':
                comment.deleted = True
            
            comment.updated_at = datetime.datetime.now()
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'msg': f'批量{action}操作成功',
            'data': None
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'msg': f'批量操作失败: {str(e)}',
            'data': None
        })

@comment_bp.get('/detail/<int:comment_id>')
@authorize("cms:comment:main")
def get_comment_detail(comment_id):
    """获取评论详情"""
    try:
        comment = Comment.query.get(comment_id)
        if not comment:
            return jsonify({
                'code': 404,
                'msg': '评论不存在',
                'data': None
            })
        
        article = None
        if comment.article_id:
            article = Post.query.get(comment.article_id)
        
        comment_data = {
            'id': comment.id,
            'author': comment.author,
            'email': comment.email,
            'url': comment.url,
            'ip': comment.ip,
            'content': comment.content,
            'status': comment.status,
            'article_id': comment.article_id,
            'created_at': comment.created_at.strftime('%Y-%m-%d %H:%M:%S') if comment.created_at else '',
            'updated_at': comment.updated_at.strftime('%Y-%m-%d %H:%M:%S') if comment.updated_at else '',
            'article_title': article.title if article else '未知文章',
            'article_url': f'/article/{article.id}' if article else '#'
        }
        
        return jsonify({
            'code': 200,
            'msg': '获取成功',
            'data': comment_data
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'msg': f'获取评论详情失败: {str(e)}',
            'data': None
        })

@comment_bp.post('/reply')
@authorize("cms:comment:main")
def reply_comment():
    """回复评论"""
    try:
        data = request.get_json()
        parent_id = data.get('parent_id')
        content = data.get('content')
        article_id = data.get('article_id')
        
        if not parent_id or not content or not article_id:
            return jsonify({
                'code': 400,
                'msg': '参数不完整',
                'data': None
            })
        
        # 创建回复评论
        reply_comment = Comment(
            author='管理员',
            content=content,
            status='approved',
            article_id=article_id,
            parent_id=parent_id,
            created_at=datetime.datetime.now(),
            updated_at=datetime.datetime.now()
        )
        
        db.session.add(reply_comment)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'msg': '回复成功',
            'data': {
                'comment_id': reply_comment.id
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'msg': f'回复失败: {str(e)}',
            'data': None
        })

@comment_bp.delete('/<int:comment_id>')
@authorize("cms:comment:main")
def delete_comment(comment_id):
    """删除评论"""
    try:
        comment = Comment.query.get(comment_id)
        if not comment:
            return jsonify({
                'code': 404,
                'msg': '评论不存在',
                'data': None
            })
        
        # 软删除
        comment.deleted = True
        comment.updated_at = datetime.datetime.now()
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'msg': '删除成功',
            'data': None
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'msg': f'删除失败: {str(e)}',
            'data': None
        })

@comment_bp.get('/stats')
@authorize("cms:comment:main")
def get_comment_stats():
    """获取评论统计信息"""
    try:
        # 各状态评论数量
        status_counts = {
            'all': Comment.query.filter(Comment.deleted == False).count(),
            'pending': Comment.query.filter(and_(Comment.deleted == False, Comment.status == 'pending')).count(),
            'approved': Comment.query.filter(and_(Comment.deleted == False, Comment.status == 'approved')).count(),
            'spam': Comment.query.filter(and_(Comment.deleted == False, Comment.status == 'spam')).count(),
            'trash': Comment.query.filter(and_(Comment.deleted == False, Comment.status == 'trash')).count()
        }
        
        # 今日评论数
        today = datetime.datetime.now().date()
        today_comments = Comment.query.filter(
            and_(
                Comment.deleted == False,
                db.func.date(Comment.created_at) == today
            )
        ).count()
        
        # 本周评论数
        week_start = today - datetime.timedelta(days=today.weekday())
        week_comments = Comment.query.filter(
            and_(
                Comment.deleted == False,
                db.func.date(Comment.created_at) >= week_start
            )
        ).count()
        
        return jsonify({
            'code': 200,
            'msg': '获取成功',
            'data': {
                'status_counts': status_counts,
                'today_comments': today_comments,
                'week_comments': week_comments
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'msg': f'获取统计信息失败: {str(e)}',
            'data': None
        })

@comment_bp.post('/init_sample_data')
@authorize("cms:comment:main")
def init_sample_data():
    """初始化示例数据（仅用于测试）"""
    try:
        # 检查是否已有数据
        existing_count = Comment.query.count()
        if existing_count > 0:
            return jsonify({
                'code': 400,
                'msg': '数据库中已有评论数据，无需初始化',
                'data': None
            })
        
        # 创建示例评论数据
        sample_comments = [
            {
                'author': '一位 WordPress 评论者',
                'email': 'wapuu@wordpress.example',
                'url': 'cn.wordpress.org',
                'ip': '192.168.1.100',
                'content': '您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。',
                'status': 'approved',
                'article_id': 1,
                'created_at': datetime.datetime(2025, 6, 27, 12, 38)
            },
            {
                'author': 'postmagt_admin',
                'email': 'support@postmagthemes.com',
                'url': 'postmagthemes.com/democontext',
                'ip': '27.34.23.45',
                'content': 'Hello',
                'status': 'approved',
                'article_id': 2,
                'created_at': datetime.datetime(2023, 3, 21, 9, 37)
            },
            {
                'author': '张三',
                'email': 'zhangsan@example.com',
                'url': 'zhangsan.com',
                'ip': '192.168.1.101',
                'content': '这篇文章写得很好，对我很有帮助！',
                'status': 'pending',
                'article_id': 1,
                'created_at': datetime.datetime.now() - datetime.timedelta(hours=2)
            },
            {
                'author': '李四',
                'email': 'lisi@example.com',
                'url': '',
                'ip': '192.168.1.102',
                'content': '感谢分享，学习了！',
                'status': 'spam',
                'article_id': 3,
                'created_at': datetime.datetime.now() - datetime.timedelta(days=1)
            },
            {
                'author': '王五',
                'email': 'wangwu@example.com',
                'url': 'wangwu.net',
                'ip': '192.168.1.103',
                'content': '这个观点很有意思，值得深入思考。',
                'status': 'trash',
                'article_id': 2,
                'created_at': datetime.datetime.now() - datetime.timedelta(days=3)
            }
        ]
        
        # 批量插入数据
        for comment_data in sample_comments:
            comment = Comment(**comment_data)
            db.session.add(comment)
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'msg': f'成功初始化 {len(sample_comments)} 条示例评论数据',
            'data': {
                'count': len(sample_comments)
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'msg': f'初始化示例数据失败: {str(e)}',
            'data': None
        })